package blue.blog.util;

import blue.blog.core.model.CmsDoc;
import blue.blog.core.model.CmsDocFile;
import blue.blog.core.service.CmsDocService;
import com.alibaba.fastjson.JSONArray;
import com.blue.core.dict.State;
import com.blue.core.http.HttpInvoker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author zhengjin
 * @since 1.0 2018年02月23日
 */
@Component
public class BlogSync
{
	private static Logger logger = LoggerFactory.getLogger(BlogSync.class);

	@Resource
	private HttpInvoker httpInvoker;
	@Resource
	private CmsDocService cmsDocService;
	@Value("${crawler.root}")
	private String root;

	public BlogSync()
	{
	}

	public void sync() throws IOException
	{
		String json = httpInvoker.get(Const.DOC_STATE);
		List<Integer> idList = JSONArray.parseArray(json, Integer.class);
		logger.info("同步id：{}", idList);
		cmsDocService.state(idList, State.DELETE.getIndex());
	}
	
	public void clear()
	{
		CmsDoc param = new CmsDoc();
		param.setState(1);
		List<CmsDoc> docList = null;
		int i = 1;
		do
		{
			docList = cmsDocService.listDetail(param, Const.PAGE_SIZE);
			for (CmsDoc doc : docList)
			{
				List<CmsDocFile> fileList = doc.getFileList();
				if (fileList == null || fileList.isEmpty())
					continue;
				
				for (CmsDocFile file : fileList)
				{
					File pic = new File(root + file.getPath());
					File thumbPic = new File(root + file.getThumbPath());
					pic.delete();
					thumbPic.delete();
				}
				cmsDocService.state(doc.getId(), Const.DOC_STATE_CLEAR);
				logger.info("{} 删除成功", doc.getTitle());
			}
			logger.info("完成页数：{}", i);
			i++;
		} while (docList != null && !docList.isEmpty());
		logger.info("完成");
		
	}

}
